package com.ssps.front.ternant.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Hala Zhou
 * @time 2020/07/22 20:01:03
 */
public class MyUtils {

    private static ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 解析json数据
     *
     * @param json
     * @return
     */
    public static Map<String, String> parse(String json) {
        Map<String, String> map = new HashMap<>();
        JavaType jvt = MAPPER.getTypeFactory().constructParametricType(HashMap.class, String.class, String.class);
        try {
            Map<String, String> urMap = MAPPER.readValue(json, jvt);
            map = urMap;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } finally {
            return map;
        }

    }

    /**
     * 获取当前时间，格式为（yyyyMMdd）
     *
     * @return 时间字符串
     */
    public static String getNowTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }

    /**
     * 产生n位随机数字
     *
     * @param n 随机的位数
     * @return 随机数字符串
     */
    public static String getRandom(int n) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < n; i++) {
            int random = (int) (Math.random() * 10);
            str.append(random);
        }
        return str.toString();
    }

    /**
     * 查看本机wlan所在ip
     *
     * @return
     */
    public static String getLocalIP() {
        try {
            Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
            while (nifs.hasMoreElements()) {
                NetworkInterface nif = nifs.nextElement();
                if (nif.getName().startsWith("wlan")) {
                    Enumeration<InetAddress> addresses = nif.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = addresses.nextElement();
                        // 速度快于 instanceof
                        if (addr.getAddress().length == 4) {
                            return addr.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "无";
    }

}
